<template>
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? $t('add') : $t('update')"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             label-width="120px">
      <el-form-item prop="name"
                    :label="$t('custom.template.fields.name')">
        <el-input v-model="dataForm.name"
                  :placeholder="$t('custom.template.fields.name')"></el-input>
      </el-form-item>
      <el-form-item prop="type"
                    :label="$t('custom.template.fields.type')">
        <el-select v-model="dataForm.type"
                   filterable
                   clearable
                   :placeholder="$t('custom.template.fields.type')"
                   default-first-option>
          <el-option v-for="its in ['teams_message','email']"
                     :key="its"
                     :label="its"
                     :value="its"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('custom.template.fields.template')">
        <div style="margin-bottom:10px;">
          <el-select v-model="selectedFields"
                     filterable
                     clearable
                     :placeholder="$t('custom.template.fields.source')"
                     default-first-option
                     style="margin-bottom:10px;">
            <el-option v-for="its in templateParamsList"
                       :key="its.id"
                       :label="its.name"
                       :value="its.id"></el-option>
          </el-select>
          <br>
          <el-tooltip v-for="(its,ii) in fieldsList"
                      :key="ii"
                      :open-delay="1000"
                      :content="its.des"
                      placement="top">
            <el-button size="mini"
                       @click="insertFields(its.fields)"
                       icon="el-icon-plus"
                       type="primary"
                       plain
                       style="margin-right:10px;margin-left:0;margin-bottom: 10px;">{{ its.fields }}</el-button>
          </el-tooltip>

        </div>
        <div id="J_quillEditor"></div>
        <el-upload :action="uploadUrl"
                   :show-file-list="false"
                   :before-upload="uploadBeforeUploadHandle"
                   :on-success="uploadSuccessHandle"
                   style="display: none;">
          <el-button ref="uploadBtn"
                     type="primary"
                     size="small">{{ $t('upload.button') }}</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button size="small"
                 @click="closeDialog">{{ $t('cancel') }}</el-button>
      <el-button size="small"
                 type="primary"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import { debounce } from 'lodash'

import Quill from 'quill'

export default {
  name: 'add-or-edit-template',
  data () {
    return {
      visible: false,
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block', 'image'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean']
      ],
      uploadUrl: '',
      dataForm: {
        id: null,
        name: null,
        type: null,
        template: null
      },
      selectedFields: null,
      templateParamsList: []
    }
  },
  computed: {
    dataRule () {
      var validateContent = (rule, value, callback) => {
        if (this.quillEditor.getLength() <= 1) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        template: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { validator: validateContent, trigger: 'blur' }
        ]
      }
    },
    fieldsList () {
      try {
        let allList = this.templateParamsList.find(e => e.id === this.selectedFields).info
        return allList.filter(e => e.fields)
      } catch (error) {
        return []
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.quillEditor) {
          this.quillEditor.deleteText(0, this.quillEditor.getLength())
        } else {
          this.quillEditorHandle()
        }
        if (this.dataForm.id) {
          this.getInfo()
        }
        this.getTemplateParamsList()
      })
    },
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      this.quillEditor.on('text-change', (delta, oldDelta, source) => {
        this.dataForm.template = this.quillEditor.root.innerHTML
        if (source === 'api') {
          // log('API triggered', delta, oldDelta)
        } else if (source === 'user') {
          // log('User triggered', delta, oldDelta)
        }
      })
    },
    customBolt () {
      let Block = Quill.import('blots/block')
      let Delta = Quill.import('delta')
      class FieldsBlot extends Block {
        convert (html = null) {
          if (typeof html === 'string') {
            this.container.innerHTML = html
          }
          let text = this.container.innerText
          this.container.innerHTML = ''
          return new Delta().insert(text)
        }
      }
      FieldsBlot.blotName = 'fields'
      FieldsBlot.tagName = 'BUTTON'
      Quill.register(FieldsBlot)
    },
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
    },
    uploadSuccessHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.src)
    },
    insertFields (value) {
      if (!value) {
        return false
      }
      this.quillEditor.focus()
      value = ` {${value}}`
      let selection = this.quillEditor.getSelection()
      let nowIndex = 0
      if (selection) {
        nowIndex = selection.index
      }
      this.quillEditor.insertText(nowIndex, value, {
        'color': '#17B3A3',
        'bold': true
      })

      setTimeout(() => {
        this.quillEditor.insertText(this.quillEditor.getSelection(), ' ', {
          'color': '#000000',
          'bold': false
        })
      }, 0)
    },
    getInfo () {
      this.$interface.schedule.getTemplateInfoApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = res.data
          this.quillEditor.root.innerHTML = this.dataForm.template
        }).catch(() => { })
    },
    validatePass (rule, value, callback) {
      let params = {
        name: this.dataForm.name,
        id: this.dataForm.id ? this.dataForm.id : ''
      }
      this.$interface.um.checkTemplateName(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error(res.msg))
          }
          callback()
        })
    },
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        const changeSysMailTemplate = () => {
          if (!this.dataForm.id) {
            return this.$interface.schedule.saveTemplateInfoApi(this.dataForm)
          } else {
            return this.$interface.schedule.updateTemplateInfoApi(this.dataForm)
          }
        }
        changeSysMailTemplate().then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.beforeClose()
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    getTemplateParamsList () {
      this.$interface.schedule.getTemplateFieldsListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.templateParamsList = res.data
        }).catch(() => { })
    },
    closeDialog () {
      this.visible = false
      this.beforeClose()
    },
    beforeClose (done) {
      // Object.assign(this.$data, this.$options.data())
      this.selectedFields = null
      this.dataForm = this.$options.data().dataForm
      if (typeof done === 'function') {
        done()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
